﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace HomeWP
{
    public partial class SettingsPage : PhoneApplicationPage
    {
        private HomeMaticData hmData = ((App)App.Current).HMData;
        private HMDataContext hMDB = ((App)App.Current).HMData.DataContext;
        private bool GotFirstError=false;

        public SettingsPage()
        {
            InitializeComponent();
            IsLoading = false;
        }


        public bool IsLoading
        {
            set
            {
                bt_loadDevices.IsEnabled = !value;
                TB_CCUAddress.IsEnabled = !value;
                bt_resetDB.IsEnabled = !value && (hmData.DataContext.HMDevices.Count()>0); 
                pgLoading.Visibility = (value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
                tB_PleaseWait.Visibility = (value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
                tbPlaseWaitSndLine.Visibility = (value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
                tbInfo.Visibility = (!value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed);
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                // Define the query to gather all of the to-do items.

                ShowDBInfo();

                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") > 0)
                {
                    CCUSettings CCUSet = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");
                    if (string.IsNullOrEmpty(CCUSet.CCU))
                        TB_CCUAddress.IsEnabled = true;
                    else
                    {
                        TB_CCUAddress.Text = CCUSet.CCU;
                    }
                }


                // Call the base method.
                base.OnNavigatedTo(e);
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }

        private void ShowDBInfo()
        {
            if (hmData.DataContext.HMDevices.Count() > 0)
                tbInfo.Text = String.Format("{0} Geräte, {1} Räume, {2} Funktionen", hmData.DataContext.HMDevices.Count(), hmData.DataContext.HMRoom.Count(), hmData.DataContext.HMFunction.Count());
            else
                tbInfo.Text = "Keine Homematic Geräte geladen!";
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            // Call the base method.
            base.OnNavigatedFrom(e);

            // Save changes to the database.
            try
            {
                hMDB.SubmitChanges();
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }


        private void bt_loadDevices_Click(object sender, RoutedEventArgs e)
        {
            if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                MessageBox.Show("Keine Netzerkverbindung vorhanden!", "Verbindungsfehler", MessageBoxButton.OK);
                return;
            }
            IsLoading = true;

            try
            {
                hmData.LoadingFinished += hmData_LoadingFinished;
                hmData.LoadingError += hmData_LoadingError;
                hmData.CCUAddress = TB_CCUAddress.Text;
                GotFirstError = false;
                hmData.Load();
        
            }
            catch
            {
                IsLoading = false;
                MessageBox.Show("Die Homematic-Zentrale (CCU) ist nicht erreichbar!", "Verbindungsfehler", MessageBoxButton.OK);
            }
        }

        void hmData_LoadingError(object sender, EventArgs e)
        {
            IsLoading = false;
            // as of the async loading, multiple error may occur simultain. just show the first
            if (!GotFirstError)
            {
                GotFirstError = true;
                HomeMaticData.LoadingErrorEventArgs ea = (HomeMaticData.LoadingErrorEventArgs)e;
                MessageBox.Show(ea.Message, "Verbindungsfehler", MessageBoxButton.OK);
            }
        }

        void hmData_LoadingFinished()
        {
            IsLoading = false;
            ShowDBInfo();

            NavigationService.RemoveBackEntry();
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));

        }       


        private void bt_resetDB_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult mb = MessageBox.Show("Möchten Sie alle Daten dieser App löschen? Die App wird dazu geschlossen.", "Daten löschen", MessageBoxButton.OKCancel);

            if (mb == MessageBoxResult.OK)
            {
              
         
            try
            {
                hmData.Dispose();

                hmData = new HomeMaticData();
                // Create the database if it does not exist.
                using (HMDataContext db = new HMDataContext(HMDataContext.DBConnectionString))
                {
                    if (db.DatabaseExists() == true)
                    {
                        //Create the database
                        try
                        {
                            db.DeleteDatabase();
                        }
                        catch
                        {
                            MessageBox.Show("Die Datenbank kann momentan nicht zurückgesetzt werden. \rBitte schliessen Sie die Applikation und versuchen Sie es erneut.", "Fehler", MessageBoxButton.OK);
                        }
                    }
                }



                ((App)App.Current).Terminate();               
            }
            catch
            {
                MessageBox.Show("Die Datenbank kann momentan nicht zurückgesetzt werden. \rBitte schliessen Sie die Applikation und versuchen Sie es erneut.", "Fehler", MessageBoxButton.OK);
            }
            }

        }


        private void TB_CCUAddress_LostFocus(object sender, RoutedEventArgs e)
        {
            try
            {
                if (hMDB.HMCCUSettings.Count(t => t.ConfigID == "TEST") > 0)
                {
                    CCUSettings CCUSet = hMDB.HMCCUSettings.Single(t => t.ConfigID == "TEST");
                    if (CCUSet.CCU != TB_CCUAddress.Text)
                    {
                        CCUSet.CCU = TB_CCUAddress.Text;
                        hMDB.SubmitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButton.OK);
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
           
                          
        }
    }
}